#include <stdio.h>
#include <stdlib.h>
#include <csp_spu.h>
#include <csp_debug.h>
#include "pi.h"
#include "config.h"

int global_pid; 

int Run(){
	int i;
	double sum = 0.0;
	double dy = GRAIN;
	double dx = GRAIN;
	double total = (1/dx)*(1/dy);
	slave_arg_t sarg __attribute__ ((aligned(16)));
	double sum_part __attribute__ ((aligned(16)));


	csp_channel master2slaves;
	csp_channel slaves2master;


	/* et lignende lipspe-program skal dele en kø med tasks */
	master2slaves = csp_create_channel(ONE2ANY_CHANNEL, MASTER2SLAVES, sizeof(slave_arg_t));
	slaves2master = csp_create_channel(ANY2ONE_CHANNEL, SLAVES2MASTER, sizeof(double));
	double share = 1.0 / (double) N;	
	for(i=0; i < N; i++){
		sarg.dx = dx;
		sarg.dy = dy;
		sarg.y  = i*share;
		sarg.y_max = sarg.y + share;
		csp_channel_write(master2slaves, &sarg);
	}

	for(i=0; i < N; i++){
		csp_channel_read(slaves2master, &sum_part);
		sum += sum_part;
	}

	printf("PI is %f\n", (sum*4)/total);

	return 0;
}
